module utils.filemime;

pragma(lib,"magic");

import std.string;

pragma(inline,true)
string getFileMime(const ubyte[] data)
{
	return fromStringz(magic_buffer(cookie,data.ptr,data.length)).dup;
}

pragma(inline,true)
string getFileMime(string file)
{
	return fromStringz(magic_file(cookie,file.toStringz)).dup;
}

private:

static ~this()
{
    if(_cookie)
            magic_close(_cookie);
}

@property cookie()
{
	if(_cookie is null){
		_cookie = magic_open(MAGIC_MIME);
		magic_load(_cookie,null);
	}
	return _cookie;
}

magic_t _cookie = null;

private:
enum int MAGIC_MIME_TYPE = 0x0000010;
enum int MAGIC_MIME_ENCODING =	0x0000400;
enum int MAGIC_MIME = (MAGIC_MIME_TYPE|MAGIC_MIME_ENCODING);

extern(C) {
	struct magic_set;
	alias magic_t = magic_set *;
	magic_t magic_open(int);
	void magic_close(magic_t);
	int magic_load(magic_t, const(char) *);
	
	const(char) * magic_getpath(const(char) *, int);
	const(char) * magic_file(magic_t, const(char) *);
	const(char) * magic_descriptor(magic_t, int);
	const(char) * magic_buffer(magic_t, const(void) *, size_t);
}
 
public:
import file = std.file;
import std.stdio;

void main()
{
    ubyte[] data = cast(ubyte[])file.read("/home/dsby/Spectacle.E161583.png", 64);
    writeln(getFileMime(data)); // image/png
    writeln(getFileMime("/home/dsby/Spectacle.E161583.png")); //image/png
    
    
    data = cast(ubyte[])file.read("/home/dsby/7893_Catch.jpg", 64);
    writeln(getFileMime(data)); //image/jpeg
    writeln(getFileMime("/home/dsby/7893_Catch.jpg")); //image/jpeg

    data = cast(ubyte[])file.read("/home/dsby/下载/BetterC.pdf", 64);
    writeln(getFileMime(data)); //application/pdf
    writeln(getFileMime("/home/dsby/下载/BetterC.pdf")); //application/pdf
    
    data = cast(ubyte[])file.read("/home/dsby/下载/jiaoda/net/2.mp4", 64);
    writeln(getFileMime(data)); //video/mp4
    writeln(getFileMime("/home/dsby/下载/jiaoda/net/2.mp4")); //video/mp4
    
}
